package com.diligent.cloud.sfc.factory.impl;

import com.alibaba.fastjson.JSON;
import com.canny.commons.model.Codes;
import com.canny.commons.model.ObjectResult;
import com.canny.commons.model.Result;
import com.canny.commons.page.IPage;
import com.canny.commons.page.Pagination;
import com.diligent.cloud.primary.data.feign.service.mdm.MdmMatTypeFeignService;
import com.diligent.cloud.primary.data.model.mdm.MdmMatType;
import com.diligent.cloud.sfc.factory.StationFactory;
import com.diligent.cloud.sfc.model.MatType;
import com.diligent.cloud.sfc.model.OrderType;
import com.diligent.cloud.sfc.model.detail.ShelfOrderDetailInfo;
import com.diligent.cloud.sfc.service.ISfcService;
import com.diligent.cloud.sfc.service.WipService;
import com.diligent.cloud.sfc.util.ConverterUtil;
import com.diligent.cloud.web.model.PageAndCondition;
import com.diligent.cloud.wip.core.vo.StorageLedgerInfo;
import com.diligent.cloud.wip.panel.modle.WipStorageLedger;
import com.diligent.cloud.workorder.enums.WoOrderStatus;
import com.diligent.cloud.workorder.model.WoOrder;
import com.diligent.cloud.workorder.model.WoOrderMatNeed;
import com.diligent.cloud.workorder.service.WoOrderFeignService;
import com.diligent.cloud.workorder.service.WoOrderMatNeedFeignService;
import com.diligent.foundation.data.model.v2.Condition;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * SprayingStation class
 *
 * @author xf107278
 * @date 3/31/2020
 */
@Component
public class UpShelfStation implements StationFactory {
    private ISfcService sfcService;
    private WoOrderFeignService orderFeignService;
    private WipService wipService;
    private final MdmMatTypeFeignService matTypeFeignService;
    private final WoOrderMatNeedFeignService orderMatNeedFeignService;

    public UpShelfStation(ISfcService sfcService, WoOrderFeignService orderFeignService, WipService wipService,
                          MdmMatTypeFeignService matTypeFeignService,
                          WoOrderMatNeedFeignService orderMatNeedFeignService) {
        this.sfcService = sfcService;
        this.orderFeignService = orderFeignService;
        this.wipService = wipService;
        this.matTypeFeignService = matTypeFeignService;
        this.orderMatNeedFeignService = orderMatNeedFeignService;
    }

    @Override
    public Result getOrderInfo(WoOrder order) {
        ShelfOrderDetailInfo shelfOrderDetailInfo = new ShelfOrderDetailInfo();
        //未完工同色
        int sameOrderNotFinished = (Integer) orderFeignService.selectSameColorWoOrderNum(order.getMachineCode(),
                order.getColorGroupCode(), WoOrderStatus.schedulings.getStatus(), OrderType.表面处理工单).getBody().getData();
        shelfOrderDetailInfo.setSameOrderNotFinished(sameOrderNotFinished - 1);
        //已完工同色
        shelfOrderDetailInfo.setSameOrderFinished((Integer) orderFeignService.selectSameColorWoOrderNum(order.getMachineCode(), order.getColorGroupCode(), WoOrderStatus.finish.getStatus(), OrderType.表面处理工单).getBody().getData());

        shelfOrderDetailInfo.setPlannedDigit(BigDecimal.valueOf(Double.parseDouble(order.getCv2())));
        shelfOrderDetailInfo.setPlannedWeight(BigDecimal.valueOf(Double.parseDouble(order.getCv4())));

        //获取当前机台已上架工单
        double bmArea = 0.0;
        double bmWeight = 0.0;
        double bmStock = 0;

        double powderStock = 0;
        double powderStockSameColor = 0;
        double powderPlanNum = Double.parseDouble(order.getCv2());
        List<Map> woOrders = (List<Map>) orderFeignService.selectUpWoOrder(order.getMachineCode(), "未上架",
                OrderType.表面处理工单).getBody().getData();
        for (Map map : woOrders) {
            WoOrder woOrder = JSON.parseObject(JSON.toJSONString(map), WoOrder.class);
            bmArea += Double.parseDouble(woOrder.getCv1()) * Double.parseDouble(woOrder.getCv2());
            bmWeight += Double.parseDouble(woOrder.getCv4()) * Double.parseDouble(woOrder.getCv2());
            powderPlanNum += Integer.parseInt(woOrder.getCv2());
        }
        shelfOrderDetailInfo.setBmArea(bmArea);
        shelfOrderDetailInfo.setBmWeight(bmWeight);

        shelfOrderDetailInfo.setColorGroup(order.getColorGroupCode());
        shelfOrderDetailInfo.setColorDescribe(order.getColorGroupName());

        shelfOrderDetailInfo.setBmStock(bmStock);
        shelfOrderDetailInfo.setPowderStock(powderStock);
        shelfOrderDetailInfo.setPowderStockSameColor(powderStockSameColor);
        shelfOrderDetailInfo.setSpacing("-");
        addStock(powderPlanNum,shelfOrderDetailInfo,order);
        return ConverterUtil.ConverterByData(shelfOrderDetailInfo, Codes.success.getCode(), Codes.success.getMsg());
    }

    private void addStock(double powderPlanNum, ShelfOrderDetailInfo shelfOrderDetailInfo, WoOrder order) {

        double powderStock = 0;
        double bmStock = 0;
        double powderStockSameColor = 0;
        double bmStockSameColor = 0;

        PageAndCondition pageAndCondition = new PageAndCondition();
        Pagination pagination = new Pagination(1L, 10000L);
        pageAndCondition.setPagination(pagination);
        List<Condition> conditions = new ArrayList<>();

        List<String> produceDates = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = formatter.format(new Date());

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        Date time = calendar.getTime();
        String yesDate = formatter.format(time);
        produceDates.add(nowDate);
        produceDates.add(yesDate);
        List<Integer> orderStatus = new ArrayList<>();
        orderStatus.add(WoOrderStatus.schedulings.getStatus());
        orderStatus.add(WoOrderStatus.inproduction.getStatus());

        Condition condition = new Condition("name", "eq", MatType.粉末, null);
        PageAndCondition pageAndCondition2 = new PageAndCondition();
        pageAndCondition2.setPagination(new Pagination(1L, 1L));
        List<Condition> conditions1 = new ArrayList<>();
        conditions1.add(condition);
        pageAndCondition2.setConditions(conditions1);
        //粉末物料类型
        MdmMatType mdmMatType = matTypeFeignService.selectDataByConditionPage(pageAndCondition2).getBody().getData
                ().getRecords().stream().findFirst().get();


        //查当班工单
        Condition machineCondition = new Condition("machineCode", "eq", order.getMachineCode(), null);
        Condition produceDateCondition = new Condition("produceDate", "in", produceDates, null);
        Condition orderTypeCondition = new Condition("orderType", "eq", OrderType.表面处理工单, null);
        Condition orderStatusCondition = new Condition("orderStatus", "in", orderStatus, null);

        conditions.add(machineCondition);
        conditions.add(produceDateCondition);
        conditions.add(orderTypeCondition);
        conditions.add(orderStatusCondition);
        pageAndCondition.setConditions(conditions);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOrder>>> resultResponseEntity =
                orderFeignService.page(pageAndCondition);
        List<WoOrder> orders = resultResponseEntity.getBody().getData().getRecords();
        List<StorageLedgerInfo> spakLedgerInfos = new ArrayList<>();
        List<StorageLedgerInfo> ledgerInfos = new ArrayList<>();
        //TODO 优化速度慢问题
        for (WoOrder woOrder : orders) {
            //胚料型号
            String matCode = woOrder.getMatCode();
            //胚料batchCode
            String batchCode = woOrder.getBatchCode();
            StorageLedgerInfo storageLedgerInfo = new StorageLedgerInfo();
            storageLedgerInfo.setMatCode(matCode);
            storageLedgerInfo.setBatchCode(batchCode);
            ledgerInfos.add(storageLedgerInfo);


            //查工单物料需求，粉
            List conditionList = new ArrayList();
            Condition condition1 = new Condition("woOrderId", "eq", woOrder.getId(), null);
            Condition condition2 = new Condition("matType", "eq", mdmMatType.getCode(), null);
            conditionList.add(condition1);
            conditionList.add(condition2);
            PageAndCondition pageAndCondition3 = new PageAndCondition();
            pageAndCondition3.setConditions(conditionList);
            pageAndCondition3.setPagination(new Pagination(1L, 1L));
            WoOrderMatNeed woOrderMatNeed = orderMatNeedFeignService.page(pageAndCondition3).getBody().getData()
                    .getRecords().stream().findFirst().get();
            //粉型号
            String matCode1 = woOrderMatNeed.getMatCode();
            //粉BatchCode
            String batchCode1 = woOrderMatNeed.getCv1();

            //粉库存查询实体
            StorageLedgerInfo storageLedgerInfo1 = new StorageLedgerInfo();
            storageLedgerInfo1.setMatCode(matCode1);
            storageLedgerInfo1.setBatchCode(batchCode1);
            spakLedgerInfos.add(storageLedgerInfo1);

            powderStock += Double.parseDouble(woOrder.getCv5());

        }


        shelfOrderDetailInfo.setColorGroup(order.getColorGroupCode());
        shelfOrderDetailInfo.setColorDescribe(order.getColorGroupName());


        WipStorageLedger storageLedger = (WipStorageLedger) wipService.getInventoryByMatCodeAndCwocCodes(order
                .getWorkCenterCode(), order.getSystemId(), ledgerInfos).getBody().getData();
        if (powderPlanNum ==0){
            shelfOrderDetailInfo.setBmStock(0.0);
        }else{
            bmStock = storageLedger.getDigit().longValue() / powderPlanNum;
            //胚料备料进度当班
            shelfOrderDetailInfo.setBmStock(bmStock);
        }

        //查同色工单工单
        Condition sameColorCondition = new Condition("colorGroupCode", "eq", order.getColorGroupCode(), null);
        PageAndCondition pageAndCondition1 = new PageAndCondition();
        pageAndCondition1.setPagination(new Pagination(1L, 10000L));
        conditions.add(sameColorCondition);
        pageAndCondition1.setConditions(conditions);

        //查同色工单工单
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOrder>>> resultResponseEntity1 =
                orderFeignService.page(pageAndCondition1);
        List<WoOrder> orders1 = resultResponseEntity1.getBody().getData().getRecords();

        List<StorageLedgerInfo> storageLedgerInfos = new ArrayList<>();
        List<StorageLedgerInfo> storageLedgerInfos1 = new ArrayList<>();
        for (WoOrder woOrder : orders1) {
            //查工单物料需求，粉
            List conditionList = new ArrayList();
            Condition condition1 = new Condition("woOrderId", "eq", woOrder.getId(), null);
            Condition condition2 = new Condition("matType", "eq", mdmMatType.getCode(), null);
            conditionList.add(condition1);
            conditionList.add(condition2);
            PageAndCondition pageAndCondition3 = new PageAndCondition();
            pageAndCondition3.setConditions(conditionList);
            pageAndCondition3.setPagination(new Pagination(1L, 1L));
            WoOrderMatNeed woOrderMatNeed = orderMatNeedFeignService.page(pageAndCondition3).getBody().getData()
                    .getRecords().stream().findFirst().get();
            //粉型号
            String matCode = woOrderMatNeed.getMatCode();
            //粉BatchCode
            String batchCode = woOrderMatNeed.getCv1();

            //粉库存查询实体
            StorageLedgerInfo storageLedgerInfo = new StorageLedgerInfo();
            storageLedgerInfo.setMatCode(matCode);
            storageLedgerInfo.setBatchCode(batchCode);
            storageLedgerInfos.add(storageLedgerInfo);

            //胚料库存查询实体
            StorageLedgerInfo storageLedgerInfo1 = new StorageLedgerInfo();
            storageLedgerInfo1.setBatchCode(woOrder.getBatchCode());
            storageLedgerInfo1.setMatCode(woOrder.getMatCode());
            storageLedgerInfos1.add(storageLedgerInfo1);
            powderStockSameColor += Double.parseDouble(woOrder.getCv5());

        }
        //查询同色工单胚料库存
        ResponseEntity<ObjectResult> responseEntity = wipService.getInventoryByMatCodeAndCwocCodes(order
                .getWorkCenterCode(), order.getSystemId(), storageLedgerInfos1);
        WipStorageLedger wipStorageLedger = (WipStorageLedger) responseEntity.getBody().getData();
        BigDecimal bigDecimal = wipStorageLedger.getDigit();

        //胚料备料进度同色
        if (powderPlanNum == 0){
            shelfOrderDetailInfo.setBmStockSameColor(0.0);
        }else{
            bmStockSameColor = bigDecimal.longValue() / powderPlanNum;
            shelfOrderDetailInfo.setBmStockSameColor(bmStockSameColor);
        }



        //查询粉末备料进度(当班)
        ResponseEntity<ObjectResult> responseEntity2 = wipService.getInventoryByMatCodeAndCwocCodes(order
                .getWorkCenterCode(), order.getSystemId(), spakLedgerInfos);
        WipStorageLedger wipStorageLedger2 = (WipStorageLedger) responseEntity2.getBody().getData();
        BigDecimal bigDecima2 = wipStorageLedger2.getDigit();
        if (powderStock == 0) {
            shelfOrderDetailInfo.setPowderStock(0.0);
        } else {
            //粉末备料进度同色
            powderStock = bigDecima2.longValue() / powderStock;
            shelfOrderDetailInfo.setPowderStock(powderStock);
        }
        //查询同色粉末库存
        ResponseEntity<ObjectResult> responseEntity1 = wipService.getInventoryByMatCodeAndCwocCodes(order
                .getWorkCenterCode(), order.getSystemId(), storageLedgerInfos);
        WipStorageLedger wipStorageLedger1 = (WipStorageLedger) responseEntity1.getBody().getData();
        BigDecimal bigDecimal1 = wipStorageLedger1.getDigit();
        if (powderStockSameColor == 0) {
            //粉末备料进度同色
            shelfOrderDetailInfo.setPowderStockSameColor(0.0);
        } else {
            //粉末备料进度同色
            powderStockSameColor = bigDecimal1.longValue() / powderStockSameColor;
            shelfOrderDetailInfo.setPowderStockSameColor(powderStockSameColor);
        }
    }


}
